﻿using RockBus.Logging.Interfaces;
using RockBus.Pipeline.Interfaces;
using RockBus.PipelineComponent.Interfaces;
using System.Collections.Generic;
using System.Reflection;
using System.ServiceModel.Channels;

namespace RockBus.Pipeline
{
    public class Pipeline : IPipeline
    {
        public Pipeline(ILogger logger, string id, IEnumerable<IPipelineComponent> pipelineComponents)
        {
            this.Logger = logger;
            this.Id = id;
            this.PipelineComponents = new List<IPipelineComponent>(pipelineComponents);
        }

        private ILogger Logger { get; set; }

        private List<IPipelineComponent> PipelineComponents { get; set; }

        #region IPipeline

        public string Id { get; private set; }

        public Message Execute(Message message, IPipelineContext pipelineContext)
        {
            foreach (var pipelineComponent in this.PipelineComponents)
            {
                if (!pipelineComponent.Configuration.ShouldProcessMessage(message.Headers.Action))
                {
                    this.Logger.LogWarning(MethodBase.GetCurrentMethod(), "Skipping PipelineComponent with id {0}.", pipelineComponent.Configuration.Id);
                    continue;
                }

                message = pipelineComponent.Execute(message, pipelineContext);
            }
            return message;
        }

        #endregion IPipeline
    }
}